/**
 * 统一错误处理工具
 */

import { Alert } from 'react-native';

// 错误类型枚举
export enum ErrorType {
  NETWORK = 'NETWORK',
  VALIDATION = 'VALIDATION',
  AUTH = 'AUTH',
  SERVER = 'SERVER',
  UNKNOWN = 'UNKNOWN',
}

// 错误信息接口
export interface ErrorInfo {
  type: ErrorType;
  message: string;
  originalError?: any;
}

// 网络错误检测
const isNetworkError = (error: any): boolean => {
  return (
    error.name === 'TypeError' ||
    error.message?.includes('Network request failed') ||
    error.message?.includes('fetch') ||
    error.code === 'NETWORK_ERROR'
  );
};

// 认证错误检测
const isAuthError = (error: any): boolean => {
  return (
    error.status === 401 ||
    error.code === 401 ||
    error.message?.includes('Unauthorized') ||
    error.message?.includes('token')
  );
};

// 服务器错误检测
const isServerError = (error: any): boolean => {
  return (
    error.status >= 500 ||
    error.code >= 500 ||
    error.message?.includes('Internal Server Error')
  );
};

// 解析错误类型和消息
export const parseError = (error: any): ErrorInfo => {
  if (isNetworkError(error)) {
    return {
      type: ErrorType.NETWORK,
      message: '網絡連接失敗，請檢查網絡設置',
      originalError: error,
    };
  }

  if (isAuthError(error)) {
    return {
      type: ErrorType.AUTH,
      message: '登錄已過期，請重新登錄',
      originalError: error,
    };
  }

  if (isServerError(error)) {
    return {
      type: ErrorType.SERVER,
      message: '服務器暫時無法響應，請稍後重試',
      originalError: error,
    };
  }

  // 如果有具体的错误消息，使用它
  if (error.message) {
    return {
      type: ErrorType.UNKNOWN,
      message: error.message,
      originalError: error,
    };
  }

  return {
    type: ErrorType.UNKNOWN,
    message: '發生未知錯誤，請稍後重試',
    originalError: error,
  };
};

// 显示错误提示
export const showError = (error: any, title: string = '錯誤') => {
  const errorInfo = parseError(error);
  
  console.error(`${title}:`, errorInfo.originalError || error);
  
  Alert.alert(title, errorInfo.message);
};

// 显示成功提示
export const showSuccess = (message: string, title: string = '成功', onPress?: () => void) => {
  Alert.alert(title, message, [
    {
      text: '確定',
      onPress,
    },
  ]);
};

// 显示确认对话框
export const showConfirm = (
  message: string,
  onConfirm: () => void,
  title: string = '確認',
  confirmText: string = '確定',
  cancelText: string = '取消'
) => {
  Alert.alert(
    title,
    message,
    [
      { text: cancelText, style: 'cancel' },
      { text: confirmText, onPress: onConfirm },
    ]
  );
};

// 显示删除确认对话框
export const showDeleteConfirm = (
  itemName: string,
  onConfirm: () => void,
  title: string = '確認刪除'
) => {
  showConfirm(
    `確定要刪除「${itemName}」嗎？此操作無法撤銷。`,
    onConfirm,
    title,
    '刪除',
    '取消'
  );
};

// 表单验证工具
export class FormValidator {
  private errors: string[] = [];

  // 重置錯誤
  reset() {
    this.errors = [];
    return this;
  }

  // 驗證必填字段
  required(value: string, fieldName: string) {
    if (!value || !value.trim()) {
      this.errors.push(`請輸入${fieldName}`);
    }
    return this;
  }

  // 驗證電郵格式
  email(value: string, fieldName: string = '電郵') {
    if (value && value.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value.trim())) {
        this.errors.push(`請輸入有效的${fieldName}地址`);
      }
    }
    return this;
  }

  // 驗證手機號格式
  phone(value: string, fieldName: string = '手機號碼') {
    if (value && value.trim()) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(value.trim())) {
        this.errors.push(`請輸入有效的${fieldName}`);
      }
    }
    return this;
  }

  // 驗證長度
  length(value: string, min: number, max: number, fieldName: string) {
    if (value && value.trim()) {
      const length = value.trim().length;
      if (length < min || length > max) {
        this.errors.push(`${fieldName}長度應在${min}-${max}個字符之間`);
      }
    }
    return this;
  }

  // 驗證數字
  number(value: string, fieldName: string, min?: number, max?: number) {
    if (value && value.trim()) {
      const num = parseFloat(value.trim());
      if (isNaN(num)) {
        this.errors.push(`請輸入有效的${fieldName}`);
      } else {
        if (min !== undefined && num < min) {
          this.errors.push(`${fieldName}不能小於${min}`);
        }
        if (max !== undefined && num > max) {
          this.errors.push(`${fieldName}不能大於${max}`);
        }
      }
    }
    return this;
  }

  // 獲取驗證結果
  validate(): boolean {
    if (this.errors.length > 0) {
      Alert.alert('輸入錯誤', this.errors[0]);
      return false;
    }
    return true;
  }

  // 獲取所有錯誤
  getErrors(): string[] {
    return [...this.errors];
  }
}

// 創建表單驗證器實例
export const createValidator = () => new FormValidator();
